# APIの基底クラス

class API

    def initialize

        require "cgi"
        require "cgi/session"

        @cgi = CGI.new;
        @session = CGI::Session.new(@cgi, {
            "tmpdir" => "/home/kjirou/tmp/rb",
            "session_key" => "_obm_session",
        })
        print @cgi.header({"type" => "text/plain"})

        @users_file = "data/users.txt"
        @bookmarks_file = "data/bookmarks.txt"
    end

    public
    def check_auth
        set_auth_to_session(@cgi["login_id"], @cgi["login_password"])
        if @session["auth"] == "1" then
            return true
        end
        false
    end

    private
    def set_auth_to_session(login_id, login_password)
        if login_id.length > 0 && login_password.length > 0 then
            @session["auth"] = "0"
            get_users.each do |user|
                if user["login_id"] == login_id && user["login_password"] == login_password
                    @session["auth"] = "1"
                    break
                end
            end
        elsif @session["auth"] == nil
            @session["auth"] = "0"
        end
    end

    def get_users
        users = []
        require "csv"
        CSV.open(@users_file, "r") do |row|
            next if row[0] == nil
            user = {
                "login_id" => row[0],
                "login_password" => row[1],
            }
            users.push(user)
        end
        return users
    end

    def get_bookmarks
        bookmarks = []
        require "csv"
        CSV.open(@bookmarks_file, "r") do |row|
            bookmarks.push({
                "url" => row[0],
                "title" => row[1],
                "tags" => row[2].split(/\t+/),
                "comment" => row[3],
            })
        end
        return bookmarks
    end

    def get_raw_bookmarks
        bookmarks = []
        require "csv"
        CSV.open(@bookmarks_file, "r") do |row|
            bookmarks.push(row)
        end
        return bookmarks
    end

    def get_tags
        tags = []
        get_bookmarks().each() do |bookmark|
            next if bookmark["tags"] == ""
            tags.concat(bookmark["tags"])
        end
        return tags.uniq()
    end
end

